package cn.itcast.bos.web.action;

import cn.itcast.bos.domain.constant.Constants;
import cn.itcast.bos.utils.MailUtils;
import cn.itcast.bos.utils.SmsDemoUtils;
import cn.itcast.bos.web.action.common.BaseAction;
import cn.itcast.crm.domain.Customer;
import com.aliyuncs.exceptions.ClientException;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.cxf.jaxrs.client.WebClient;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Controller;

import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.Session;
import javax.ws.rs.core.MediaType;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;


/**
 * Created by Think on 2017/9/21.
 */
@ParentPackage("json-default")
@Namespace("/")
@Controller
@Scope(value = "prototype")
public class CustomerAction extends BaseAction<Customer>{

    //注入jmsTemplate
    @Autowired
    @Qualifier("jmsQueueTemplate")
    JmsTemplate jmsTemplate;

    @Action(value = "customer_sendSms",results = {@Result(name = SUCCESS,type = "json")})
    public String sendSms() throws ClientException {
        // 手机号保存在Customer对象
        final String telephone = model.getTelephone();
        // 生成短信验证码（RandomStringUtils.randomNumeric(4);
        final String randomCode = SmsDemoUtils.getNumber();
        // 将手机号和验证码放置到Session中一份，用于注册的时候用
        ServletActionContext.getRequest().getSession().setAttribute(telephone,randomCode);
        // session（60秒过期）
        ServletActionContext.getRequest().getSession().setMaxInactiveInterval(60);
//        SendSmsResponse sendSmsResponse = SmsDemoUtils.sendSms(telephone, randomCode);
//        String code = sendSmsResponse.getCode();
        // 使用短信平台系统（bos_sms）负责发送短信，使用消息队列ActiveMQ，此时bos_fore生产者
        jmsTemplate.send("bos_sms", new MessageCreator() {
            @Override
            public Message createMessage(Session session) throws JMSException {
                MapMessage mapMessage = session.createMapMessage();
                mapMessage.setString("telephone",telephone);
                mapMessage.setString("code",randomCode);
                return mapMessage;
            }
        });
        // 假设验证成功（正常开发被注释，为了方便测试）
        String code = "OK";
        // 发送成功
        if(code.equals("OK")){
            Map<String, Object> map = new HashMap<String,Object>();
            map.put("success",randomCode);
            map.put("telephone", telephone);
            map.put("code",randomCode);
            ServletActionContext.getContext().getValueStack().push(map);
        }else{
            throw new RuntimeException("发送短信失败,请联系管理员");
        }
        return SUCCESS;
    }

    /**
     * 注册功能
     */
    //获取验证码
    private String checkcode;

    public void setCheckcode(String checkcode) {
        this.checkcode = checkcode;
    }

    @Action(value = "customer_regist",results = {@Result(name = SUCCESS,type = "redirect",location = "signup-success.html"),
                                                @Result(name = INPUT,type = "redirect",location = "signup.html")})
    public String regist(){
        // 先校验短信验证码，如果不通过，调回注册页面
        // 从session获取 之前生成验证码
        String code = (String) ServletActionContext.getRequest().getSession().getAttribute(model.getTelephone());//存储session是,属性名是telephone,值时randomCode
        //判断session中的code和页面填写的checkcode
        if(code==null || !code.equals(checkcode)){
            System.out.println("输入验证码有误!");
            return INPUT;
        }
        //完成注册
        WebClient.create(Constants.CRM_MANAGEMENT_URL+"/services/customerService/customer")
                .type(MediaType.APPLICATION_JSON)
                .post(model);
        System.out.println("注册成功");

        /**向redis数据库存放邮件的激活码，激活码生命周期1天（24小时）*/
        // 生成32位的激活码
        String activecode = RandomStringUtils.randomNumeric(32);
        redisTemplate.opsForValue().set(model.getTelephone(),activecode,24, TimeUnit.HOURS);
        String content = "尊敬的客户您好，请于24小时内，进行邮箱账户的绑定，点击下面地址完成绑定:<br/><a href='"
                + MailUtils.activeUrl + "?telephone=" + model.getTelephone()
                + "&activecode=" + activecode + "'>速运快递邮箱绑定地址</a>";
        //发送激活邮件到用户注册用的邮箱,等待用户激活
        MailUtils.sendMail("速运快递到你家",content,model.getEmail(),"");
        return SUCCESS;
    }



    @Autowired
    RedisTemplate<String,String> redisTemplate;

    // 邮件激活码
    private String activecode;

    public void setActivecode(String activecode) {
        this.activecode = activecode;
    }

    @Action(value="customer_activeMail")
    public String activeMail() throws IOException{
        // 在浏览器上显示中文，处理中文的乱码
        ServletActionContext.getResponse().setContentType("text/html;charset=UTF-8");
        System.out.println(activecode);
        // 判断邮件的激活码是否过期
        // 从redis数据库中获取邮件的激活码
        String code = redisTemplate.opsForValue().get(model.getTelephone());
        if(code == null || !code.equals(activecode)){
            ServletActionContext.getResponse().getWriter().println("激活码无效，请登录系统，重新绑定邮箱！");
        }
        // 使用手机号查询CRM的数据库，判断当前手机号是否已经被绑定激活
        Customer c = WebClient.create(Constants.CRM_MANAGEMENT_URL)
                .path("/services/customerService/customer/telephone/"+model.getTelephone())
                .type(MediaType.APPLICATION_JSON)
                .accept(MediaType.APPLICATION_JSON)
                .get(Customer.class);
        // 可以完成注册
        if(c!=null && c.getType()!=1){
            WebClient.create(Constants.CRM_MANAGEMENT_URL)
                    .path("/services/customerService/customer/updatetype/"+model.getTelephone())
                    .type(MediaType.APPLICATION_JSON)
                    .put(null);
            ServletActionContext.getResponse().getWriter().println("邮箱注册绑定成功！");
        }
        // 已经注册
        else{
            ServletActionContext.getResponse().getWriter().println("邮箱已经绑定过，无需重复绑定！");
        }
        // 根据手机号删除redis数据库
        redisTemplate.delete(model.getTelephone());
        return NONE;
    }

    /**登录*/
    @Action(value="customer_login",results={@Result(name="success",type="redirect",location="./index.html#/myhome"),
            @Result(name="input",type="redirect",location="./login.html")})
    public String login() throws Exception{
        // 获取手机账号和密码
        String telephone = model.getTelephone();
        String password = model.getPassword();
        // 调用webservice
        Customer customer = WebClient.create(Constants.CRM_MANAGEMENT_URL+"/services/customerService/customer/findByTelephoneAndPassword?telephone="+telephone+"&password="+password)
                .type(MediaType.APPLICATION_JSON)
                .accept(MediaType.APPLICATION_JSON)
                .get(Customer.class);
        // 此时不存在该用户
        if(customer==null){
            System.out.println("当前账号和密码输入有误！");// 回去之后大家可以动手改成jsp，在jsp上输出错误信息！
            return INPUT;
        }
        else{
            System.out.println("当前账号和密码输入正确！");
            if(customer.getType()!=1){
                System.out.println("当前账号没有激活，请登录邮箱去激活！");// 回去之后大家可以动手改成jsp，在jsp上输出错误信息！
                return INPUT;
            }
            else{
                // 将账号和密码存放到Session中
                ServletActionContext.getRequest().getSession().setAttribute("customer", customer);
            }
        }
        return SUCCESS;
    }
}
